<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="设备号">

        <el-input style="width: 250px;" v-model="dataForm.equNumber" placeholder="请输入设备号" clearable></el-input>


      </el-form-item>
      <el-form-item v-if="roleId!=2" label="用户名">
        <el-input style="width: 250px;" v-model="dataForm.userNames" placeholder="请输入用户名" clearable></el-input>
      </el-form-item>
      <el-form-item label="设备状态">
        <el-select v-model="dataForm.equStatus" placeholder="选择设备状态">
          <el-option v-for="item in options.status" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 30px;">
        <el-button @click="getDataList()">查询</el-button>
        <!-- <el-button v-if="roleId!=2" type="primary" @click="addOrUpdateHandle()">新增</el-button> -->
        <el-button v-if="roleId!=2" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">
          批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column prop="index" header-align="center" align="center" label="序号">
      </el-table-column>
      <el-table-column prop="equNumber" header-align="center" align="center" label="设备号">

      </el-table-column>
      <!-- <el-table-column prop="equName" header-align="center" align="center" label="设备名">
      </el-table-column> -->
      <!-- <el-table-column
        prop="userids"
        header-align="center"
        align="center"
        label="用户Id">
      </el-table-column> -->
      <el-table-column v-if="roleId!=2" prop="userNames" header-align="center" align="center" label="用户名">
      </el-table-column>
      <el-table-column prop="equStatus" header-align="center" align="center" label="设备状态">
        <!--        <template slot-scope="{row}">
          <el-tag v-text="row.equStatus==1?'正常':'异常'" size="small">{{row.equStatus}}</el-tag>

        </template> -->
      </el-table-column>
      <el-table-column prop="equElectric" header-align="center" align="center" label="设备电量">
      </el-table-column>

      <el-table-column prop="updateTime" header-align="center" align="center" label="创建时间">
      </el-table-column>


      <el-table-column fixed="right" header-align="center" align="center" width="220" label="操作">
        <template slot-scope="scope">
          <el-button v-if="roleId!=2" type="text" size="small" @click="lookOrUpdateHandle(scope.row.equNumber)">设备日志
          </el-button>
          <el-button type="text" size="small" @click="lookLog(scope.row.id)">设备详情</el-button>
          <el-button v-if="roleId!=2" type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <!-- 弹窗详情 -->
    <lookLog v-if="lookLogShow" ref="lookLoge"></lookLog>
  </div>
</template>

<script>
  import AddOrUpdate from './equipment-add-or-update'
  import lookLog from './lookLog'
  export default {
    data() {
      return {
        options: {
          status: [{
            value: '正常',
            label: '正常'
          }, {
            value: '异常',
            label: '异常'
          }, {
            value: '',
            label: '全部'
          }, ]
        },
        dataForm: {
          equNumber: '',
          userNames: '',

        },
        id: null,
        roleId: null, //获得自己的角色id用于执行一些操作
        lookid: '',
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        lookLogShow: false,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        formUser: null,
      }
    },
    components: {
      AddOrUpdate,
      lookLog
    },
    activated() {

      if (this.$route.query.id) {
        this.id = this.$route.query.id
        this.formUser = this.$route.query.formUser

      } else {
        // this.getUserInfo()
        this.id = window.localStorage.getItem('userId')
        this.roleId = window.localStorage.getItem('roleId')
      }
      this.getDataList()

    },
    methods: {
      // 表单提交
      // getUserInfo() {
      //   this.$http({
      //     url: this.$http.adornUrl(`/sys/user/info`),
      //     method: 'get',
      //   }).then((data) => {

      //     console.log(data.data.user.userId)
      //     this.id = data.data.user.userId
      //     this.getDataList()
      //   })


      // },
      lookOrUpdateHandle(equNumber) {
        console.log('equNumber', equNumber)
        this.$router.push('/messlog-messlog?equNumber=' + equNumber)
      },
      lookLog(id) {
        this.lookLogShow = true
        this.$nextTick(() => {
          this.$refs.lookLoge.init(id)
        })

      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/equ/manage/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            ids: this.id,
            'equNumber': this.dataForm.equNumber,
            'userNames': this.dataForm.userNames,
            equStatus: this.dataForm.equStatus
          })
        }).then(({
          data
        }) => {
          console.log('列表', data)
          if (data && data.code === 0) {

            this.dataList = data.page.records
            this.totalPage = data.page.total

            for (var i = 0; i < this.dataList.length; i++) {
              this.dataList[i].index = i + 1
            }


          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
        console.log(this.dataListSelections)
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle(row) {

        if (row) {
          var userNames = row.userNames.split(',')

          var userIds = row.userIds.split(',')
          var roleId = window.localStorage.getItem('roleId')
          var userId = window.localStorage.getItem('userId')
          var userName = window.localStorage.getItem('username')
          var index = userNames.indexOf(userName)
          var index2 = userIds.indexOf(userId)
          var adminIndex = userNames.indexOf('admin')
          var adminindex2 = userIds.indexOf(1)
          if (adminIndex == -1) {
            userIds.splice(index2, 1, '1')
            userNames.splice(index, 1, 'admin')
          } else {
            userIds.splice(index2, 1)
            userNames.splice(index, 1)
          }
        }


        var ids = row ? [row.id] : this.dataListSelections.map(item => {
          return item.id
        })
        //提示信息改为设备名
        var equNames = row ? [row.equName] : this.dataListSelections.map(item => {
          console.log(item)
          return item.equName
        })

        console.log(userNames, userIds, userId, userName, index, adminIndex, adminindex2)
        this.$confirm(`确定对设备进行[${row ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (roleId == 2) {
            this.$http({
              url: this.$http.adornUrl(`/equ/manage/update`),
              method: 'post',
              data: this.$http.adornData({
                id: Number(ids),
                userIds: userIds.toString(),
                userNames: userNames.toString(),
                equName: row.equName,
                equNumber: row.equNumber,
                equStatus: row.equStatus
              })
            }).then(({
              data
            }) => {
              console.log(data)
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',

                })
                this.getDataList()
              } else {
                this.$message.error(data.msg)
              }
            })
          } else {
            this.$http({
              url: this.$http.adornUrl('/equ/manage/delete'),
              method: 'post',
              data: this.$http.adornData(ids, false)
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 10,
                  onClose: () => {
                    this.getDataList()
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }

        })
      }
    }
  }
</script>
